package com.ryder.book_cycle.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ryder.book_cycle.common.response.Result;
import com.ryder.book_cycle.entity.Book;
import com.ryder.book_cycle.service.BookService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述: 书籍表(Book)表控制层
 * 
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025-07-09 02:36:43
 */
@RestController
@RequestMapping("/book")
public class BookController {

    private static final Logger log = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private BookService bookService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result<Page<Book>> pageList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam Long merchantId,
            @RequestParam(required = false) String bookName) {
        try {
            Page<Book> page = new Page<>(pageNum, pageSize);
            Book book = new Book();
            book.setMerchantId(merchantId);
            book.setTitle(bookName);
            QueryWrapper<Book> wrapper = new QueryWrapper<>();
            wrapper.eq("merchant_id", merchantId);
            if (StringUtils.isNotBlank(bookName)) {
                wrapper.like("title", bookName);
            }
            Page<Book> result = bookService.page(page, wrapper);
            log.info("分页条数：{}", result.getRecords().size());
            result.getRecords().forEach(b -> log.info("图书ID: {}, 标题: {}", b.getId(), b.getTitle()));
            return Result.ok(result);
        } catch (Exception e) {
            log.error("分页查询失败：{}", e.getMessage(), e);
            return Result.fail("分页异常");
        }
    }

    /**
     * 分页查询
     */
    @GetMapping("/userPage")
    public Result<Page<Book>> userPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize,
            @RequestParam(required = false) String bookName,
            @RequestParam(required = false) String author) {
        try {
            Page<Book> page = new Page<>(pageNum, pageSize);
            Book book = new Book();
            book.setTitle(bookName);
            book.setAuthor(author);
            QueryWrapper<Book> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(bookName)) {
                wrapper.like("title", bookName);
            }
            if (StringUtils.isNotBlank(author)) {
                wrapper.like("author", author);
            }
            wrapper.eq("status", 1);
            Page<Book> result = bookService.page(page, wrapper);
            log.info("分页条数：{}", result.getRecords().size());
            result.getRecords().forEach(b -> log.info("图书ID: {}, 标题: {}", b.getId(), b.getTitle()));
            return Result.ok(result);
        } catch (Exception e) {
            log.error("分页查询失败：{}", e.getMessage(), e);
            return Result.fail("分页异常");
        }
    }

    /**
     * 根据主键查询
     */
    @GetMapping("/{id}")
    public Result<Book> queryById(@PathVariable Long id) {
        try {
            Book entity = bookService.getById(id);
            return entity != null ? Result.ok(entity) : Result.fail("未找到数据");
        } catch (Exception e) {
            log.error("查询失败：{}", e.getMessage(), e);
            return Result.fail("查询异常");
        }
    }

    /**
     * 新增
     */
    @PostMapping
    public Result<Boolean> add(@RequestBody Book entity) {
        try {
            boolean isMerchant = bookService.existsMerchantId(entity.getMerchantId());
            if (!isMerchant) {
                return Result.fail("商家不存在");
            }
            boolean saved = bookService.save(entity);
            return saved ? Result.ok(true) : Result.fail("新增失败");
        } catch (Exception e) {
            log.error("新增失败：{}", e.getMessage(), e);
            return Result.fail("新增异常");
        }
    }

    /**
     * 修改
     */
    @PutMapping
    public Result<Boolean> update(@RequestBody Book entity) {
        try {
            boolean updated = bookService.updateById(entity);
            return updated ? Result.ok(true) : Result.fail("更新失败");
        } catch (Exception e) {
            log.error("更新失败：{}", e.getMessage(), e);
            return Result.fail("更新异常");
        }
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        try {
            boolean removed = bookService.removeById(id);
            return removed ? Result.ok(true) : Result.fail("删除失败");
        } catch (Exception e) {
            log.error("删除失败：{}", e.getMessage(), e);
            return Result.fail("删除异常");
        }
    }

}
